//
//  CityHunterViewController.m
//  GOGOTravel
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "CityHunterViewController.h"
#import "SecondViewController.h"
#import "GiFHUD.h"
@interface CityHunterViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UISegmentedControl *segment;

@property (nonatomic, retain) BaseTableView *tableView;

@property (nonatomic, retain) NSMutableArray *productArr;/**<  装model的数组 */
@property (nonatomic, retain) NSIndexPath *indexPathCZ;/**<  button点击传值 */
@property (nonatomic, assign) BOOL isHeader;/**<  判断上下拉刷新 */
@property (nonatomic, assign) NSInteger page;/**<  记录next_start */
@property (nonatomic, assign) NSInteger pageResult;/**<  urlPage */
@property (nonatomic, retain) UIButton *button3;
@property (nonatomic, retain) UIButton *button4;
@property (nonatomic, retain) UIButton *button5;

@property (nonatomic, retain) UIButton *itemButton;/**<  左边的item */
@property (nonatomic, copy) NSString *urlCityName;
@property (nonatomic, retain) ProductTableViewCell *cell;


@property (nonatomic, retain) UIBarButtonItem *item;
@end

@implementation CityHunterViewController

- (void)dealloc{
    
    
    [_button3 release];
    [_button4 release];
    [_button5 release];

    [_item release];
    [_itemButton release];
    [_urlCityName release];
    [_cell release];
    
    [_indexPathCZ release];
   [_tableView release];
    [_productArr release];
    [_segment release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.urlCityName = @"北京";
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.9 green:0.29 blue:0.44 alpha:1];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"城市猎人带你玩";
    self.view.backgroundColor = UIColorFromRGB(0xF0F0F0);
    
    self.productArr = [NSMutableArray array];
    
    [self initRightItem];
    [self initTableView];
    [self handleData];
    [self initheader];
    [self initFooter];
    _page = 0;
    
    [GiFHUD setGifWithImageName:@"b879f2e742d94b2a8f2362d0ca7e18c7.gif"];
    [GiFHUD show];
}

#pragma mark- MJRe
- (void)initheader{
    
    [_tableView addHeaderWithCallback:^{
        _page = 0;
        _isHeader = YES;
        [self handleData];
    }];
    
    
}

- (void)initFooter{
    
    [_tableView addFooterWithCallback:^{
        self.page = _pageResult;
        _isHeader = NO;
        
        [self handleData];
    }];
    
}

#pragma mrak- tableView
- (void)initTableView{

    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    //注册
    [_tableView registerClass:[ProductTableViewCell class] forCellReuseIdentifier:@"ProductTableViewCell"];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    /**<  判断数据数组是否为空 */
    if (_productArr.count) {
        
        return _productArr.count;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 300;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"ProductTableViewCell"];
    _cell.selectionStyle = UITableViewCellAccessoryNone;
   
    if (_productArr.count) {
        Product *model = _productArr[indexPath.row];
        _cell.model = model;
        
    }
    
    
    
    return _cell;
}
/**<  点击方法 *///http://web.breadtrip.com/hunter/product/11372/?bts=app_tab
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /**<  判断数据源数组是否为空 */
    if (_productArr.count) {
        Product *model = _productArr[indexPath.row];
        NSString *product_id = [model.product_id stringValue];
        NSString *url = @"http://web.breadtrip.com/hunter/product/11372/?bts=app_tab";
        NSString *result = [url stringByReplacingCharactersInRange:NSMakeRange(40, 5) withString:product_id];
        NSLog(@"%@", result);
        
        ExperienceDetailsViewController *ex = [[ExperienceDetailsViewController alloc] init];
        ex.url = result;
        [self.navigationController pushViewController:ex animated:YES];
        [ex release];
        
    }
}


/**<  设置左button */
- (void)initRightItem {
    
    self.itemButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _itemButton.frame = CGRectMake(0, 0, 100, 30);
    [_itemButton setTitle:@"北京" forState:UIControlStateNormal];
    _itemButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_itemButton addTarget:self action:@selector(itemAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_itemButton];
    
    self.navigationItem.leftBarButtonItem =item;
    [item release];
}

/** item方法 */
- (void)itemAction:(UIBarButtonItem *)item{
    
    SecondViewController *sec = [[SecondViewController alloc] init];
    
   //block赋值传城市名过来
    sec.block = ^void(NSString *str){
        NSLog(@"1111111%@", str);
    
        //重置城市标题
        [_itemButton setTitle:str forState:UIControlStateNormal];
        //刷新数据是移除数据源移除
        [_productArr removeAllObjects];
        NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:str]];
        self.urlCityName = result;
        //刷新数据
        [self handleData];

        
    };
    
    sec.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:sec  animated:YES completion:^{
        
    }];
}

- (void)handleData{
    
    NSString *result = [NSString stringWithFormat:@"http://api.breadtrip.com/hunter/products/more/?city_name=%@&start=%ld&lat=38.8825145611238&lng=121.53913015009306",_urlCityName, (long)(long)_page ];
   
    NSString *url = [result stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:result]];
    
    [AFNetWorkingHandle GETRequestWithURLString:url completionWithSuccess:^(id result) {
        NSDictionary *dic = result;
        
        _pageResult = [dic[@"next_start"] integerValue];
        
        NSArray *arr = dic[@"product_list"];
        
        if (_isHeader == YES) {
            [_productArr removeAllObjects];
        }
        NSMutableArray *arr1 = [NSMutableArray array];
        
        arr1 = [Product ModelHandleWithArray:arr];
        
        for (Product *model in arr1) {
            [_productArr addObject:model];
        }
      
        
        [_tableView reloadData];
        
        [GiFHUD dismiss];
        
        [_tableView headerEndRefreshing];
        [_tableView footerEndRefreshing];
    } withFailure:^(id error) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
